'''
Author: goog
Date: 2021-12-13 16:45:46
LastEditTime: 2021-12-20 21:52:47
LastEditors: goog
Description: 下段检测只在10号摄像头检测
FilePath: /TensorRT_fast/DetectionZM/XD/XD.py
Time Limit Exceeded!
'''
import json
import os
import cv2
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
from torchvision.models import resnet18
from sklearn.decomposition import PCA


def xd(cfg, image, barcode, classif_net=None, device=None, is_save=False, visulization=False):
    
    # 设备
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    # 网络       
    if classif_net == None:
        classif_net = resnet18(pretrained=True).to(device)
        classif_net.eval()

    # 读配置文件
    defect = 'XD'    
    abs_dir = cfg['abs_dir']
    config_path = os.path.join(abs_dir, 'DetectionZM/'+defect+'/'+defect+'.json')
    feature_list = []
    with open(config_path) as json_file:
        config = json.load(json_file)
        if barcode not in config.keys():
            barcode = 'C50'+barcode[3:]
        c =  config[barcode]
        if c['label'] == defect.lower():
            points = c['points']
            image4 = image[c['position']]

            roi_list = []
            for point in points.values():
                ref = image4[point[0]:point[0]+point[2], point[1]:point[1]+point[3], :]
                roi_list.append(ref)
                if visulization:
                    cv2.rectangle(image4, (point[0], point[1]), (point[0]+point[2], point[1]+point[3]), color=(0, 255, 255), thickness=5)
                    cv2.putText(image4, defect, (point[0], point[1] - 2), 0, 3 / 3, [225, 255, 255], thickness=3, lineType=cv2.LINE_AA)
            
            if visulization:
                cv2.imwrite(os.path.join(abs_dir, 'Test', defect.upper()+".png"), image4)
        else:
            return False    

    defect_feature_path =  os.path.join(abs_dir, 'DetectionZM', defect, barcode+'.npy')              
    # 保存特征    
    if is_save:
        # feature_dict = {}
        # for ind, ft in enumerate(feature_list):
        #     feature_dict[str(ind+1)] = ft 
        feature_np = np.array(feature_list)
        np.save(defect_feature_path, feature_np)
    else:
        # 加载特征
        tem_feature = np.load(defect_feature_path, allow_pickle=True)  
        fl = np.array(feature_list) 
        tf = np.array(tem_feature)    
        sub= np.mean(np.abs(fl-tf), axis=-1)
        if np.sum(sub)>20:
            return False
        else:
            return True
    
    return False   


if __name__ == "__main__":
    ref = cv2.imread('./Templates/C50/FR-L/169.254.7.10.jpg')
    ref = cv2.cvtColor(ref, cv2.COLOR_BGR2RGB)
           
    xd(ref, "C50FR-L", is_save=True)

            
            


# '''
# Author: goog
# Date: 2021-12-13 16:45:46
# LastEditTime: 2021-12-20 12:51:21
# LastEditors: goog
# Description: 下段检测只在10号摄像头检测
# FilePath: /TensorRT_fast/DetectionZM/XD/XD.py
# Time Limit Exceeded!
# '''
# import json
# import os
# import cv2
# import torch
# import numpy as np
# from PIL import Image
# from torchvision import transforms
# from torchvision.models import resnet18
# from sklearn.decomposition import PCA
# import sys
# # sys.path.append("./DetectionZM")

# def xd(cfg, image4, barcode, classif_net=None, device=None, is_save=False, visulization=False):
#     image4 = image4.copy()
#     # if device is not None:
#     device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
            
#     if classif_net == None:
#         classif_net = resnet18(pretrained=True).to(device)
#         classif_net.eval()
    
#     abs_dir = cfg['abs_dir']
#     defect = 'XD'
#     config_path = os.path.join(abs_dir, 'DetectionZM/'+defect+'/'+defect+'.json')
#     feature_list = []
#     with open(config_path) as json_file:
#         config = json.load(json_file)
#         if config[barcode]['label'] == defect.lower():
#             points = config[barcode]['points']
#             roi_list = []
            
#             for point in points.values():
#                 # tar = template[point[0]:points[0]+points[2], points[1]:points[3], :]
#                 # print(image4.shape)
#                 ref = image4[point[0]:point[0]+point[2], point[1]:point[1]+point[3], :]
#                 roi_list.append(ref)
#                 cv2.rectangle(image4, (point[0], point[1]), (point[0]+point[2], point[1]+point[3]), color=(0, 255, 255), thickness=5)
#             if visulization:
#                 cv2.imwrite(defect.upper()+".png", image4)
#             image_transform = transforms.Compose([
#                 transforms.ToTensor(),
#                 transforms.Normalize(mean=(0.485, 0.456, 0.406),
#                                  std=(0.229, 0.224, 0.225))
#             ])
            
#             for ind, img in enumerate(roi_list):
#                 # print(img.shape)
#                 I_img = Image.fromarray(img)
#                 t_img = image_transform(I_img)
#                 t_img = t_img.unsqueeze(0)
#                 t_img = t_img.to(device)
#                 with torch.no_grad():
#                     feature = classif_net(t_img)
#                     f_n = feature.data.cpu().numpy()
#                     feature_list.append(f_n)
                    
#     # 保存特征    
#     if is_save:
#         # feature_dict = {}
#         # for ind, ft in enumerate(feature_list):
#         #     feature_dict[str(ind+1)] = ft 
#         feature_np = np.array(feature_list)
#         np.save('./DetectionZM/XD/XD'+barcode+'.npy', feature_np)        

#     # 加载特征
#     tem_feature = np.load('./DetectionZM/XD/XD.npy', allow_pickle=True)  
#     fl = np.array(feature_list) 
#     tf = np.array(tem_feature)    
#     sub= np.mean(np.abs(fl-tf), axis=-1)
#     if np.sum(sub)>20:
#         return False
#     # for ft, tf in zip(feature_list, tem_feature.item().values()):
        
#     #     print(ft.shape)
#     #     print(tf.shape)
#     #     # pca = PCA(n_components=10).fit(ft)
#     #     # p = pca.transform(ft)
#     #     # print(pca.shape)
#     return True   






# if __name__ == "__main__":
#     ref = cv2.imread('./Templates/C50/FR-L/169.254.7.10.jpg')
#     ref = cv2.cvtColor(ref, cv2.COLOR_BGR2RGB)
           
#     xd(ref, "C50FR-L", is_save=True)

            
            

